<template>
  <div class="app-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #409EFF;">
              <i class="el-icon-money"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.totalReceivable || 0 }}</div>
              <div class="stat-label">总应收金额</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #67C23A;">
              <i class="el-icon-success"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.totalReceived || 0 }}</div>
              <div class="stat-label">已收金额</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #E6A23C;">
              <i class="el-icon-warning"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.totalOutstanding || 0 }}</div>
              <div class="stat-label">待收金额</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #F56C6C;">
              <i class="el-icon-user"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.customerCount || 0 }}</div>
              <div class="stat-label">客户数量</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索表单 -->
    <el-card shadow="hover" class="mb20">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="客户名称" prop="customerName">
          <el-input
            v-model="queryParams.customerName"
            placeholder="请输入客户名称"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="月份" prop="month">
          <el-date-picker
            v-model="queryParams.month"
            type="month"
            value-format="yyyy-MM"
            placeholder="请选择月份"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['poring:poring:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['poring:poring:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['poring:poring:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['poring:poring:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-view"
          size="mini"
          @click="handleViewDetails"
          :disabled="single"
        >详情</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table
        v-loading="loading"
        :data="poringList"
        @selection-change="handleSelectionChange"
        stripe
        border
        highlight-current-row
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="月份" align="center" prop="month" width="120">
          <template slot-scope="scope">
            <el-tag type="primary">{{ parseTime(scope.row.month, '{y}-{m}') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="客户名称" align="center" prop="customerName" min-width="150">
          <template slot-scope="scope">
            <el-link type="primary" @click="handleViewCustomer(scope.row)">{{ scope.row.customerName }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="付款方式" align="center" prop="paymentMethod" width="120">
          <template slot-scope="scope">
            <el-tag :type="getPaymentMethodType(scope.row.paymentMethod)">{{ scope.row.paymentMethod }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="月结天数" align="center" prop="monthlySettlementDays" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.monthlySettlementDays }}天</span>
          </template>
        </el-table-column>
        <el-table-column label="对账截止日" align="center" prop="reconciliationDeadline" width="140">
          <template slot-scope="scope">
            <el-tag :type="getDeadlineType(scope.row.reconciliationDeadline)">
              {{ parseTime(scope.row.reconciliationDeadline, '{m}-{d}') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="交易币种" align="center" prop="transactionCurrency" width="100">
          <template slot-scope="scope">
            <el-tag type="info">{{ scope.row.transactionCurrency }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="应收金额" align="center" prop="receivableAmount" width="120">
          <template slot-scope="scope">
            <span class="amount receivable">{{ formatAmount(scope.row.receivableAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="已收金额" align="center" prop="receivedAmount" width="120">
          <template slot-scope="scope">
            <span class="amount received">{{ formatAmount(scope.row.receivedAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="尚欠款金额" align="center" prop="outstandingAmount" width="120">
          <template slot-scope="scope">
            <span class="amount outstanding" :class="{ 'warning': scope.row.outstandingAmount > 0 }">
              {{ formatAmount(scope.row.outstandingAmount) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="收款进度" align="center" width="120">
          <template slot-scope="scope">
            <el-progress
              :percentage="getProgressPercentage(scope.row)"
              :color="getProgressColor(scope.row)"
              :stroke-width="8"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleViewDetails(scope.row)"
            >详情</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['poring:poring:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['poring:poring:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改应收款月份报对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="月份" prop="month">
              <el-date-picker
                clearable
                v-model="form.month"
                type="month"
                value-format="yyyy-MM"
                placeholder="请选择月份"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="form.customerName" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="付款方式" prop="paymentMethod">
              <el-select v-model="form.paymentMethod" placeholder="请选择付款方式" style="width: 100%">
                <el-option label="现金" value="现金" />
                <el-option label="银行转账" value="银行转账" />
                <el-option label="支票" value="支票" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="月结天数" prop="monthlySettlementDays">
              <el-input-number
                v-model="form.monthlySettlementDays"
                :min="0"
                :max="365"
                placeholder="请输入月结天数"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="对账截止日" prop="reconciliationDeadline">
              <el-date-picker
                clearable
                v-model="form.reconciliationDeadline"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择对账截止日"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交易币种" prop="transactionCurrency">
              <el-select v-model="form.transactionCurrency" placeholder="请选择币种" style="width: 100%">
                <el-option label="人民币" value="CNY" />
                <el-option label="美元" value="USD" />
                <el-option label="欧元" value="EUR" />
                <el-option label="日元" value="JPY" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="应收金额" prop="receivableAmount">
              <el-input
                v-model.number="form.receivableAmount"
                placeholder="请输入应收金额"
                type="number"
                @input="calculateOutstanding"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="已收金额" prop="receivedAmount">
              <el-input
                v-model.number="form.receivedAmount"
                placeholder="请输入已收金额"
                type="number"
                @input="calculateOutstanding"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="尚欠款金额" prop="outstandingAmount">
              <el-input
                v-model.number="form.outstandingAmount"
                placeholder="自动计算"
                readonly
                style="background-color: #f5f7fa"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="应收款详情" :visible.sync="detailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="月份">{{ parseTime(selectedRow.month, '{y}-{m}') }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ selectedRow.customerName }}</el-descriptions-item>
        <el-descriptions-item label="付款方式">{{ selectedRow.paymentMethod }}</el-descriptions-item>
        <el-descriptions-item label="月结天数">{{ selectedRow.monthlySettlementDays }}天</el-descriptions-item>
        <el-descriptions-item label="对账截止日">{{ parseTime(selectedRow.reconciliationDeadline, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="交易币种">{{ selectedRow.transactionCurrency }}</el-descriptions-item>
        <el-descriptions-item label="应收金额" :span="2">
          <span class="amount receivable">{{ formatAmount(selectedRow.receivableAmount) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="已收金额" :span="2">
          <span class="amount received">{{ formatAmount(selectedRow.receivedAmount) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="尚欠款金额" :span="2">
          <span class="amount outstanding" :class="{ 'warning': selectedRow.outstandingAmount > 0 }">
            {{ formatAmount(selectedRow.outstandingAmount) }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="收款进度" :span="2">
          <el-progress
            :percentage="getProgressPercentage(selectedRow)"
            :color="getProgressColor(selectedRow)"
            :stroke-width="12"
          />
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ selectedRow.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { listPoring, getPoring, delPoring, addPoring, updatePoring } from "@/api/poring/poring"

export default {
  activated() {
    this.getList()
  },
  name: "Poring",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应收款月份报表格数据
      poringList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 详情对话框
      detailOpen: false,
      // 选中的行数据
      selectedRow: {},
      // 统计数据
      statistics: {
        totalReceivable: 0,
        totalReceived: 0,
        totalOutstanding: 0,
        customerCount: 0
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: null,
        month: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        month: [
          { required: true, message: "月份不能为空", trigger: "blur" }
        ],
        customerName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" }
        ],
        paymentMethod: [
          { required: true, message: "付款方式不能为空", trigger: "change" }
        ],
        monthlySettlementDays: [
          { required: true, message: "月结天数不能为空", trigger: "blur" },
          { type: 'number', min: 0, max: 365, message: "月结天数必须在0-365之间", trigger: "blur" }
        ],
        reconciliationDeadline: [
          { required: true, message: "对账截止日不能为空", trigger: "blur" }
        ],
        transactionCurrency: [
          { required: true, message: "交易币种不能为空", trigger: "change" }
        ],
        receivableAmount: [
          { required: true, message: "应收金额不能为空", trigger: "blur" },
          { type: 'number', min: 0, message: "应收金额必须大于等于0", trigger: "blur" }
        ],
        receivedAmount: [
          { required: true, message: "已收金额不能为空", trigger: "blur" },
          { type: 'number', min: 0, message: "已收金额必须大于等于0", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询应收款月份报列表 */
    getList() {
      this.loading = true
      listPoring(this.queryParams).then(response => {
        this.poringList = response.rows
        this.total = response.total
        this.calculateStatistics()
        this.loading = false
      })
    },
    // 计算统计数据
    calculateStatistics() {
      this.statistics = {
        totalReceivable: 0,
        totalReceived: 0,
        totalOutstanding: 0,
        customerCount: new Set(this.poringList.map(item => item.customerName)).size
      }

      this.poringList.forEach(item => {
        this.statistics.totalReceivable += parseFloat(item.receivableAmount || 0)
        this.statistics.totalReceived += parseFloat(item.receivedAmount || 0)
        this.statistics.totalOutstanding += parseFloat(item.outstandingAmount || 0)
      })
    },
    // 格式化金额
    formatAmount(amount) {
      if (!amount) return '0.00'
      return parseFloat(amount).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    },
    // 获取付款方式标签类型
    getPaymentMethodType(method) {
      const types = {
        '现金': 'success',
        '银行转账': 'primary',
        '支票': 'warning',
        '其他': 'info'
      }
      return types[method] || 'info'
    },
    // 获取截止日标签类型
    getDeadlineType(deadline) {
      if (!deadline) return 'info'
      const today = new Date()
      const deadlineDate = new Date(deadline)
      const diffDays = Math.ceil((deadlineDate - today) / (1000 * 60 * 60 * 24))

      if (diffDays < 0) return 'danger'
      if (diffDays <= 7) return 'warning'
      return 'success'
    },
    // 计算收款进度百分比
    getProgressPercentage(row) {
      if (!row.receivableAmount || row.receivableAmount == 0) return 0
      return Math.round((row.receivedAmount / row.receivableAmount) * 100)
    },
    // 获取进度条颜色
    getProgressColor(row) {
      const percentage = this.getProgressPercentage(row)
      if (percentage >= 100) return '#67C23A'
      if (percentage >= 80) return '#E6A23C'
      if (percentage >= 50) return '#F56C6C'
      return '#909399'
    },
    // 计算尚欠款金额
    calculateOutstanding() {
      const receivable = parseFloat(this.form.receivableAmount || 0)
      const received = parseFloat(this.form.receivedAmount || 0)
      this.form.outstandingAmount = Math.max(0, receivable - received)
    },
    // 查看详情
    handleViewDetails(row) {
      this.selectedRow = row
      this.detailOpen = true
    },
    // 查看客户信息
    handleViewCustomer(row) {
      this.$message.info(`查看客户：${row.customerName}`)
      // 这里可以跳转到客户详情页面
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        month: null,
        customerName: null,
        paymentMethod: null,
        monthlySettlementDays: null,
        reconciliationDeadline: null,
        transactionCurrency: null,
        receivableAmount: null,
        receivedAmount: null,
        outstandingAmount: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        customerName: null,
        month: null,
        paymentMethod: null,
        transactionCurrency: null,
        minAmount: null,
        maxAmount: null
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push('/poring/poring/add')
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getPoring(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改应收款月份报"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 验证已收金额不能超过应收金额
          if (parseFloat(this.form.receivedAmount) > parseFloat(this.form.receivableAmount)) {
            this.$message.error("已收金额不能超过应收金额")
            return
          }

          if (this.form.id != null) {
            updatePoring(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPoring(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除应收款月份报编号为"' + ids + '"的数据项？').then(function() {
        return delPoring(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('poring/poring/export', {
        ...this.queryParams
      }, `poring_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.mb20 {
  margin-bottom: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.mx-2 {
  margin: 0 8px;
}

// 统计卡片样式
.stat-card {
  .stat-content {
    display: flex;
    align-items: center;

    .stat-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;

      i {
        font-size: 24px;
        color: white;
      }
    }

    .stat-info {
      flex: 1;

      .stat-value {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        line-height: 1;
        margin-bottom: 5px;
      }

      .stat-label {
        font-size: 14px;
        color: #909399;
      }
    }
  }
}

// 金额样式
.amount {
  font-weight: bold;
  font-family: 'Courier New', monospace;

  &.receivable {
    color: #409EFF;
  }

  &.received {
    color: #67C23A;
  }

  &.outstanding {
    color: #F56C6C;

    &.warning {
      color: #E6A23C;
    }
  }
}

// 表格样式优化
.el-table {
  .el-table__header-wrapper {
    th {
      background-color: #f5f7fa !important;
    }
  }
}

// 搜索表单样式
.el-form--inline .el-form-item {
  margin-right: 15px;
}

// 对话框样式
.el-dialog {
  .el-dialog__body {
    padding: 20px;
  }
}

// 详情描述样式
.el-descriptions {
  .el-descriptions-item__label {
    font-weight: bold;
    color: #606266;
  }
}
</style>
